package org.openmore.opc.controller.api;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.*;
import org.openmore.common.exception.InvalidParamsException;
import org.openmore.common.exception.OpenmoreException;
import org.openmore.opc.annotation.TokenAuthCheck;
import org.openmore.opc.controller.BaseController;
import org.openmore.opc.dto.BaseResponse;
import org.openmore.opc.dto.Pagination;
import org.openmore.opc.dto.StringParams;
import org.openmore.opc.dto.api.RoleDto;
import org.openmore.opc.entity.Role;
import org.openmore.opc.entity.User;
import org.openmore.opc.framework.MyThreadLocalConfig;
import org.openmore.opc.service.RoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE;

/**
 * THIS IS AUTO GENERATED SOURCE CODE
 * Created by org.openmore
 * on 2018-08-11
 */
@Api(value = "/Role", tags = "", description = "角色")
@RequestMapping(value = "/api/role", produces = {APPLICATION_JSON_UTF8_VALUE})
@RestController
public class RoleController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RoleService roleService;

    @TokenAuthCheck
    @ApiOperation(value = "分页返回所有数据", response = RoleDto.class, responseContainer = "List")
    @ApiResponses(value = {@ApiResponse(code = 400, message = "请求失败：找不到id={id}的", response = RoleDto.class)})
    @RequestMapping(method = RequestMethod.GET, value = "/query")
    public BaseResponse selectAllByPage(
            @RequestParam(required = false, defaultValue = "") @ApiParam(value = "角色名") String name,
            @RequestParam(required = false, defaultValue = "0") @ApiParam(value = "分页第几页") Integer pageNum,
            @RequestParam(required = false, defaultValue = "0") @ApiParam(value = "每页多少记录") Integer pageSize) {
        logger.debug(">> selectAllByPage");
        List<RoleDto> resultList = null;
        User user = MyThreadLocalConfig.getUser();
//      如果是管理员，需要返回角色对应的社区名
        if (user != null) {
            if (user.getUserType().equals("ROOT")) {
                PageHelper.startPage(pageNum, pageSize);
                resultList = roleService.getDtoFullInfo(name);
                return BaseResponse.buildSuccessResponse(new Pagination(new PageInfo(resultList)), resultList);
            }
        }
        PageHelper.startPage(pageNum, pageSize);
        resultList = roleService.selectAll(null, name);
        if (resultList == null) {
            throw new InvalidParamsException("没有数据");
        }
        return BaseResponse.buildSuccessResponse(new Pagination(new PageInfo(resultList)), resultList);
    }

    @TokenAuthCheck
    @ApiOperation(value = "为角色配置权限，权限id列表，以逗号间隔", response = String.class)
    @ApiResponses(value = {@ApiResponse(code = 400, message = "请求失败：原因", response = BaseResponse.class)})
    @RequestMapping(method = RequestMethod.POST, value = "/{id}/permission")
    public BaseResponse grantPermission(
            @PathVariable @ApiParam(value = "角色id") String id,
            @RequestBody @ApiParam(value = "权限列表字符串，以逗号间隔") StringParams param) {
        logger.debug(">> grantPermission");
        roleService.grantPermission(id, param.getData());
        return BaseResponse.buildSuccessResponse("配置成功");
    }

    @TokenAuthCheck
    @ApiOperation(value = "根据id获取信息", response = RoleDto.class)
    @ApiResponses(value = {@ApiResponse(code = 400, message = "请求失败：找不到id={id}的", response = BaseResponse.class)})
    @RequestMapping(method = RequestMethod.GET, value = "/{id}")
    public BaseResponse getRoleById(@PathVariable @ApiParam(required = true, value = "id") String id) {
        logger.debug(">> getRoleById");
        try {
            RoleDto roleDto = roleService.getDtoById(id);
            if (roleDto == null) {
                throw new InvalidParamsException("请求失败：找不到id=" + id + "的");
            }
            return BaseResponse.buildSuccessResponse(roleDto);
        } catch (OpenmoreException e) {
            return BaseResponse.buildFailResponse(400, e.getMsg());
        } catch (Exception e) {
            logger.error(e.getMessage());
            return BaseResponse.buildFailResponse(400, "查询数据失败");
        }
    }

    @TokenAuthCheck
    @Transactional
    @ApiOperation("更新")
    @ApiResponses(value = {@ApiResponse(code = 400, message = "请求失败：更新的数据不存在", response = BaseResponse.class),
            @ApiResponse(code = 400, message = "请求失败：数据更新失败", response = BaseResponse.class)})
    @RequestMapping(method = RequestMethod.PUT)
    public BaseResponse updateRole(@RequestBody @ApiParam(value = "新信息", required = true) RoleDto role) {
        logger.debug(">> updateRole");
        Role entity = roleService.getEntityById(role.getId());
        if (entity == null) {
            throw new InvalidParamsException("请求失败：更新的数据不存在");
        }
        roleService.update(role);
        return BaseResponse.buildSuccessResponse("更新成功");
    }

    @TokenAuthCheck
    @Transactional
    @ApiOperation("创建")
    @ApiResponses(value = {@ApiResponse(code = 400, message = "请求失败：数据创建失败", response = BaseResponse.class)})
    @RequestMapping(method = RequestMethod.POST, consumes = {APPLICATION_JSON_UTF8_VALUE})
    public BaseResponse insertRole(@RequestBody @ApiParam(value = "创建", required = true) RoleDto role) {
        logger.debug(">> insertRole");
        RoleDto roleDto = roleService.insert(role);
        return BaseResponse.buildSuccessResponse(roleDto);
    }

    @TokenAuthCheck
    @Transactional
    @ApiOperation(value = "删除指定")
    @ApiResponses(value = {@ApiResponse(code = 400, message = "请求失败：数据删除失败", response = BaseResponse.class)})
    @RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
    public BaseResponse deleteRole(@PathVariable @ApiParam(value = "id", required = true) String id) {
        logger.debug(">> deleteRole");
        roleService.deleteById(id);
        return BaseResponse.buildSuccessResponse("数据删除成功");
    }
}




